package term

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/blog/model"
	"mall/service/blog/rpc/internal/svc"
	"mall/service/blog/rpc/internal/utils"
	"mall/service/blog/rpc/internal/utils/errorhandler"
	"mall/service/blog/rpc/types/blog"

	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreateTermLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateTermLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateTermLogic {
	return &CreateTermLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateTermLogic) CreateTerm(in *blog.TermInfo) (*blog.BaseIDResp, error) {
	// logx.Infof("CreateTerm : %+v ", in)

	var term model.BlogTerm
	var taxonomy int32
	if in.Taxonomy != nil {
		taxonomy = utils.ParseTaxonomy(strings.TrimSpace(*in.Taxonomy))
	}
	if taxonomy > 0 {
		term.Taxonomy = uint16(taxonomy)
	} else {
		term.Taxonomy = uint16(globalkey.TermTaxonomyCategory)
	}
	if in.Name != nil {
		term.Name = strings.TrimSpace(*in.Name)

		if len(term.Name) == 0 {
			return nil, errorx.NewInvalidArgumentError("term.nameRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogTermColumns.Name] = map[string][]any{
			"equalTo": {term.Name},
		}
		filterMap[model.BlogTermColumns.Taxonomy] = map[string][]any{
			"equalTo": {term.Taxonomy},
		}
		_, count, err := l.svcCtx.Term.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("term.nameAlreadyExists")
		}
	} else {
		return nil, errorx.NewInvalidArgumentError("term.nameRequired")
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if in.Slug != nil { // 允许为空，不管长度
		term.Slug = strings.TrimSpace(*in.Slug)
	}
	if in.ParentId != nil {
		term.ParentID = *in.ParentId
	}
	if in.GroupId != nil {
		term.TermGroup = *in.GroupId
	}
	if in.Desc != nil {
		term.Description = *in.Desc
	}
	if in.FilteredDesc != nil {
		term.DescriptionFiltered = *in.FilteredDesc
	}
	if in.Sort != nil {
		term.Sort = uint16(*in.Sort)
	} else {
		term.Sort = uint16(9999)
	}
	if in.Status != nil {
		term.Status = uint8(*in.Status)
	} else {
		term.Status = uint8(globalkey.StatusEnabled)
	}
	now := time.Now()
	term.CreatedAt = now
	term.UpdatedAt = now
	rel := &model.BlogTermRel{}
	if len(in.Meta) > 0 {
		for _, v := range in.Meta {
			if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
				continue
			}

			if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
				continue
			}

			rel.Meta = append(rel.Meta, &model.BlogTermMetum{
				MetaKey:   strings.TrimSpace(*v.Key),
				MetaValue: null.StringFrom(strings.TrimSpace(*v.Value)),
			})
		}
	}

	allMediaMap := make(map[string]string)
	if len(in.AllMedia) > 0 {
		for _, v := range in.AllMedia {
			if v.Id != nil && v.Url != nil && len(*v.Id) > 0 && len(*v.Url) > 0 {
				allMediaMap[*v.Id] = *v.Url
			}
		}
	}

	if len(in.NewMedia) > 0 {
		var thumbnailOrder uint
		var thumbnailId uint64
		var thumbnailUrl string
		for idx, v := range in.NewMedia {
			var url string
			if v.Url != nil && len(*v.Url) > 0 { // v.Uri  content版本（包含?id）  v.Url  url当前版本 | attachment当前版本
				url = *v.Url
			}
			var uri string
			if v.Uri != nil && len(*v.Uri) > 0 {
				uri = *v.Uri
				if len(url) == 0 {
					url = uri
				}
			}
			if len(url) == 0 {
				continue
			}

			var thumbnail uint8
			if v.Thumbnail != nil && *v.Thumbnail > 0 {
				thumbnail = uint8(*v.Thumbnail)
			}
			var order uint
			if v.Order != nil {
				order = uint(*v.Order)
			} else {
				order = uint(idx) + globalkey.AttachmentOrderOffset
			}
			var altText string
			if v.AltText != nil && len(*v.AltText) > 0 {
				altText = *v.AltText
			}

			var meta []string
			if v.Name != nil && len(*v.Name) > 0 {
				meta = append(meta, "filename:"+*v.Name)
				if len(altText) == 0 {
					altText = *v.Name
				}
			}
			if v.MetaData != nil && len(*v.MetaData) > 0 {
				meta = append(meta, *v.MetaData)
			}
			if v.MimeType != nil && len(*v.MimeType) > 0 {
				meta = append(meta, "mimeType:"+*v.MimeType)
			}
			metaData := strings.Join(meta, ";")

			var mediaId uint64
			if v.Id != nil && len(*v.Id) > 0 {
				if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
					mediaId = uint64(i)
				}
			}

			media := &model.BlogAttachmentRelationship{
				AttachmentID:        mediaId,
				AttachmentThumbnail: thumbnail,
				AttachmentOrder:     order,
				AttachmentImageURL:  url,
				AttachmentImageAlt:  altText,
				AttachmentImageMeta: metaData,
			}

			if thumbnail == 0 && mediaId > 0 { // thumbnail == 0 不是缩略图， mediaId > 0 不是外链，获取图文uri
				if uri, ok := allMediaMap[*v.Id]; ok {
					media.AttachmentSource = uri
				}
			}

			rel.Media = append(rel.Media, media)

			if thumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > order) {
				thumbnailOrder = order
				thumbnailId = mediaId
				thumbnailUrl = url
			}
		}

		if len(thumbnailUrl) > 0 {
			rel.Meta = append(rel.Meta, &model.BlogTermMetum{
				MetaKey:   "_thumbnail_id",
				MetaValue: null.StringFrom(strconv.FormatInt(int64(thumbnailId), 10)),
			})
			rel.Meta = append(rel.Meta, &model.BlogTermMetum{
				MetaKey:   "_thumbnail_url",
				MetaValue: null.StringFrom(thumbnailUrl),
			})
		}
	}

	err = l.svcCtx.Term.Insert(l.ctx, tx, &term, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &blog.BaseIDResp{
		Id:  term.TermID,
		Msg: i18n.CreateSuccess,
	}, nil
}
